<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-write-comments">
    <div class="content">
      <div class="crumbs">
        <router-link
          to="/user-center"
          class="item-a"
        >
          {{ $t('comments.personalCenter') }}
        </router-link>
        <span class="arrow">></span>
        <span
          v-if="isComm === 0"
          class="item-span"
        >{{ $t('comments.postComment') }}</span>
        <span
          v-if="isComm === 1"
          class="item-span"
        >{{ $t('comments.commentDetails') }}</span>
      </div>
      <div class="comments-con">
        <div v-if="orderItemProds.length > 0">
          <div
            v-for="(item,index) in orderItemProds"
            :key="index"
            class="comments-box"
          >
            <div class="goods-msg">
              <div class="img">
                <img-show :src="item.pic" />
              </div>
              <a
                class="name"
                href="javascript:void(0);"
                @click="toProdDetail(item.prodId)"
              >{{ item.prodName }}</a>
              <div
                v-if="item.skuName && item.skuName.trim()"
                class="sku"
              >
                {{ $t('comments.specification') }}: {{ item.skuName }}
              </div>
              <div class="order-number">
                {{ $t('comments.orderNumber') }}：
                <a
                  href="javascript:void(0);"
                  class="number"
                  @click="toOrderDetail(item.orderNumber)"
                >{{ item.orderNumber }}</a>
              </div>
              <div class="deal-time">
                {{ $t('comments.transactionTime') }}：
                <span class="number">{{ item.payTime }}</span>
              </div>
            </div>
            <!-- 待评价 -->
            <div
              v-if="isComm === 0"
              class="operation"
            >
              <div
                class="item"
                aria-disabled="true"
              >
                <div class="tit">
                  {{ $t('comments.productRating') }}
                </div>
                <!-- 评分星级: -->
                <div class="star-box">
                  <span class="stars">
                    <i
                      :class="[item.score > 0?'star':'star-gray']"
                      @click="prodComm(1,item.orderItemId)"
                    />
                    <i
                      :class="[item.score > 1?'star':'star-gray']"
                      @click="prodComm(2,item.orderItemId)"
                    />
                    <i
                      :class="[item.score > 2?'star':'star-gray']"
                      @click="prodComm(3,item.orderItemId)"
                    />
                    <i
                      :class="[item.score > 3?'star':'star-gray']"
                      @click="prodComm(4,item.orderItemId)"
                    />
                    <i
                      :class="[item.score > 4?'star':'star-gray']"
                      @click="prodComm(5,item.orderItemId)"
                    />
                  </span>
                </div>
              </div>
              <div class="item">
                <div class="tit">
                  {{ $t('comments.specificDescription') }}
                </div>
                <div class="des-box">
                  <textarea
                    v-model="item.content"
                    class="des"
                    maxlength="150"
                    :placeholder="$t('comments.provideYourComments')"
                  />
                  <div class="des-tip">
                    {{ $t('comments.enterUpTo150Characters') }}
                  </div>
                </div>
              </div>
              <div class="item">
                <div class="tit">
                  {{ $t('comments.uploadImages') }}
                </div>
                <div class="img-box">
                  <mul-pic-upload
                    v-model="item.imgs"
                    :limit="9"
                  />
                  <div class="img-des">
                    （ {{ $t('comments.uploadUpTo9Photos') }} ）
                  </div>
                </div>
              </div>
            </div>
            <!-- 已评价 -->
            <div
              v-if="isComm === 1"
              class="operation"
            >
              <div
                class="item"
                aria-disabled="true"
              >
                <div class="tit">
                  {{ $t('comments.productRating') }}
                </div>
                <!-- 评分星级: -->
                <div class="star-box">
                  <span class="stars">
                    <i
                      :class="[item.score > 0?'star':'star-gray']"
                      @click="prodComm(1)"
                    />
                    <i
                      :class="[item.score > 1?'star':'star-gray']"
                      @click="prodComm(2)"
                    />
                    <i
                      :class="[item.score > 2?'star':'star-gray']"
                      @click="prodComm(3)"
                    />
                    <i
                      :class="[item.score > 3?'star':'star-gray']"
                      @click="prodComm(4)"
                    />
                    <i
                      :class="[item.score > 4?'star':'star-gray']"
                      @click="prodComm(5)"
                    />
                  </span>
                </div>
              </div>
              <div
                class="item"
                style="margin-top: -15px;"
              >
                <div class="tit">
                  {{ $t('comments.specificDescription') }}
                </div>
                <div class="des-content">
                  <span>{{ item.content }}</span>
                </div>
              </div>
              <div class="item">
                <div class="tit">
                  {{ $t('comments.commentsOnPictures') }}
                </div>
                <div
                  v-if="item.pics.length"
                  class="img-box"
                >
                  <div
                    v-for="(pic, inx) in item.pics"
                    :key="inx"
                    class="file-img"
                  >
                    <img-show :src="pic" />
                  </div>
                </div>
                <div
                  v-if="!item.pics.length"
                  class="des-content"
                  style="color: #999;"
                >
                  {{ $t('comments.none') }}
                </div>
              </div>
              <div
                v-if="item.replyContent"
                class="item"
                style="margin-top: -15px;"
              >
                <div class="tit">
                  {{ $t('prodDetail.merchantResponse') }}
                </div>
                <div class="des-content">
                  <span>{{ item.replyContent }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- /待评价 -->
        <div class="btn-box">
          <a
            v-if="isComm === 0"
            href="javascript:void(0);"
            class="btn"
            @click="submitComm()"
          >{{ $t('comments.postComment') }}</a>
          <div
            v-if="isComm === 0"
            class="agree-box"
            @click="checkAgree"
          >
            <input
              type="checkbox"
              :class="['checkbox',isAnonymous?'checked': 'default']"
              class="checkbox default"
            >
            <span class="text">{{ $t('comments.anonymousOrNot') }}</span>
          </div>
          <a
            v-if="isComm === 1"
            href="javascript:void(0);"
            class="btn back"
            @click="cancel()"
          >{{ $t('comments.backToList') }}</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as util from '@/utils/index.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const orderItemId = ref(0)
const isComm = ref(route.query.isComm)
const orderNumber = ref(route.query.orderNumber) // 订单号
onMounted(() => {
  // 设置网页标题
  document.title = $t('ucOrder.evaluationSunshine')
  isComm.value = Number(route.query.isComm)
  orderItemId.value = Number(route.query.orderItemId) || 0
  if (isComm.value === 0 || isComm.value === 1) {
    getOrderItems(orderNumber.value)
  } else {
    isComm.value = 0
  }
})

const orderItemProds = ref([]) // 订单商品信息
/**
 * 改变商品评分
 */
const prodComm = (num, orderItemId) => {
  if (isComm.value === 1) {
    return
  }
  orderItemProds.value.forEach(orderItem => {
    if (orderItemId === orderItem.orderItemId) {
      orderItem.score = num
    }
  })
}

/**
* 获取商品评价
*/
const getComm = (orderItemIds) => {
  orderItemIds = orderItemIds.join()
  http.get('/p/prodComm/getProdComment', {
    params: {
      orderItemIds
    }
  }).then(({ data }) => {
    orderItemProds.value.forEach((orderItem) => {
      const commInfo = data.find(comm => comm.orderItemId === orderItem.orderItemId)
      orderItem.content = commInfo.content
      orderItem.replyContent = commInfo.replyContent
      orderItem.score = commInfo.score
      orderItem.pics = commInfo.pics ? commInfo.pics.split(',') : []
    })
  })
}

/**
* 获取多个商品详情
*/
const getOrderItems = (orderNumber) => {
  http.get('/p/myOrder/getOrderItems', {
    params: {
      orderNumber
    }
  }).then(({ data }) => {
    // 订单项Id集合
    const orderItemIds = []
    for (let i = 0; i < data.length; i++) {
      data[i].images = []
      data[i].content = ''
      data[i].score = 5
      data[i].evaluate = 0
      data[i].pics = []
      orderItemIds.push(data[i].orderItemId)
    }
    orderItemProds.value = data
    // 查看评论
    if (isComm.value === 1) {
      getComm(orderItemIds)
    }
  })
}

const isAnonymous = ref(false)
let submitCommCount = 0 // 已经提交了的评价数
/**
 * 提交评论
 */
const submitComm = () => {
  let allFill = true
  for (let i = 0; i < orderItemProds.value.length; i++) {
    const cont = orderItemProds.value[i].content.trim()
    if (cont === '') {
      ElMessage({
        message: $t('comments.evaluationCannotBeEmpty'),
        type: 'warning',
        duration: 1000
      })
      allFill = false
      break
    }
  }
  if (allFill) {
    const time = util.formatTime(new Date())
    for (let i = 0; i < orderItemProds.value.length; i++) {
      const prodComm = {
        orderItemId: orderItemProds.value[i].orderItemId,
        score: orderItemProds.value[i].score,
        content: orderItemProds.value[i].content,
        isAnonymous: isAnonymous.value ? 1 : 0,
        evaluate: orderItemProds.value[i].score === 3 ? 1 : orderItemProds.value[i].score < 3 ? 2 : 0,
        prodId: orderItemProds.value.prodId,
        pics: orderItemProds.value[i].imgs,
        recTime: time
      }

      http.post('/p/prodComm', prodComm).then(() => {
        submitCommCount += 1
        if (submitCommCount === orderItemProds.value.length) {
          ElMessage({
            message: $t('comments.submitCommentSuccessfully'),
            type: 'success',
            duration: 1000,
            onClose: () => {
              router.push({ path: '/user-center/uc-comments' })
            }
          })
        }
      })
    }
  }
}

/**
 * 跳转订单详情
 */
const toOrderDetail = (orderNumber) => {
  router.push({ path: '/order-detail', query: { orderNumber } })
}

/**
 * 是否匿名
 */
const checkAgree = () => {
  isAnonymous.value = !isAnonymous.value
}

/**
 * 跳转到商品详情页
 */
const toProdDetail = (prodId) => {
  const orderType = route.query.orderType
  let newPage
  if (orderType === '0') {
    newPage = router.resolve({ path: '/detail', query: { prodId } })
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  } else if (orderType === '1') {
    newPage = router.resolve({ path: '/detail', query: { prodId } })
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  } else if (orderType === '2') { // 秒杀商品
    //  秒杀商品活动是否结束
    http.get('/p/seckill/prod', {
      params: {
        prodId
      }
    }).then(({ data }) => {
      if (data) {
        newPage = router.resolve({ path: '/detail', query: { prodId } })
        window.open(newPage.href, '_blank', 'noopener,noreferrer')
      } else {
        ElMessage.warning($t('spike.currentSecondsAreOver'))
      }
    })
  }
}

/**
 * 返回
 */
const cancel = () => {
  router.push({ path: '/user-center/uc-comments', query: { isComm: 1 } })
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
